import {defineStore} from "pinia";
import {loginForm, loginResponseData} from "@/api/user/type";
import {reqLogin, reqUserInfo} from "@/api/user";
import type {UserState} from "@/store/modules/types/type";
import { constRoutes } from '@/router/routes'
import router from '@/router/index.ts'
//store暴露都以use开头
let useUserStore = defineStore('User', {
    state: (): UserState => {
        return {
            token: localStorage.getItem('TOKEN'),
            menuRoutes: constRoutes, //仓库存储生成菜单需要数组（路由）
            username: "",
            avatar: ""
        }
    },
    actions: {
        async userLogin(data: loginForm) {
            let res: loginResponseData = await reqLogin(data)
            if (res.code == 200) {
                //注意点：访问state的属性使用this直接访问，与VUE2引入state访问不同
                this.token = res.data.token as string
                localStorage.setItem('TOKEN', res.data.token as string)
                return 'ok'
            } else return Promise.reject(new Error(res.data.message as string))

        },
        //获取用户信息方法
        async userInfo() {
            //获取用户信息进行存储
            let result = await reqUserInfo()
            if (result.code == 200) {
                this.username = result.data.checkUser.username
                this.avatar = result.data.checkUser.avatar
            }
        },
        //退出登录
        async userLogout() {
            //当前没有mock接口（不做）：服务器数据token失效
            //本地数据清空
            this.token = ''
            this.username = ''
            this.avatar = ''
            localStorage.removeItem('TOKEN')
            await router.push({path: '/login'})
        },
    },
    getters: {}
})

export default useUserStore;
